package com.businesscard.system.controller;

import com.businesscard.system.entity.BusinessCard;
import com.businesscard.system.entity.BusinessCardFolder;
import com.businesscard.system.entity.User;
import com.businesscard.system.service.BusinessCardFolderService;
import com.businesscard.system.service.BusinessCardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpSession;
import java.util.*;

/**
 * 名片管理控制器
 */
@Controller
@RequestMapping("/user/businesscard")
public class BusinessCardController {

    @Autowired
    private BusinessCardFolderService folderService;

    @Autowired
    private BusinessCardService cardService;

    /**
     * 显示名片管理主页
     */
    @GetMapping
    public String index(Model model) {
        User user = getCurrentUser();
        List<BusinessCardFolder> folders = folderService.getFoldersByUserId(user.getId());

        model.addAttribute("folders", folders);
        return "user/businesscard/index";
    }

    /**
     * 显示回收站页面
     */
    @GetMapping("/recycle")
    public String recycle(Model model) {
        User user = getCurrentUser();
        List<BusinessCardFolder> deletedFolders = folderService.getDeletedFoldersByUserId(user.getId());

        model.addAttribute("deletedFolders", deletedFolders);
        return "user/businesscard/recycle";
    }

    /**
     * 创建名片夹
     */
    @PostMapping("/folder/create")
    @ResponseBody
    public Map<String, Object> createFolder(@RequestBody BusinessCardFolder folder) {
        Map<String, Object> result = new HashMap<>();

        try {
            User user = getCurrentUser();
            folder.setUserId(user.getId());

            boolean success = folderService.createFolder(folder);

            result.put("success", success);
            result.put("message", success ? "创建名片夹成功" : "创建名片夹失败");

            if (success) {
                result.put("folder", folder);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建名片夹失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 重命名名片夹
     */
    @PostMapping("/folder/rename")
    @ResponseBody
    public Map<String, Object> renameFolder(@RequestBody BusinessCardFolder folder) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCardFolder existingFolder = folderService.getFolderById(folder.getId());

            if (existingFolder == null) {
                result.put("success", false);
                result.put("message", "名片夹不存在");
                return result;
            }

            User user = getCurrentUser();
            if (!existingFolder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权重命名该名片夹");
                return result;
            }

            existingFolder.setFolderName(folder.getFolderName());
            boolean success = folderService.updateFolder(existingFolder);

            result.put("success", success);
            result.put("message", success ? "重命名名片夹成功" : "重命名名片夹失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "重命名名片夹失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 删除名片夹(移入回收站)
     */
    @PostMapping("/folder/delete/{id}")
    @ResponseBody
    public Map<String, Object> deleteFolder(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCardFolder folder = folderService.getFolderById(id);

            if (folder == null) {
                result.put("success", false);
                result.put("message", "名片夹不存在");
                return result;
            }

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权删除该名片夹");
                return result;
            }

            boolean success = folderService.deleteFolder(id);

            result.put("success", success);
            result.put("message", success ? "删除名片夹成功" : "删除名片夹失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除名片夹失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 恢复名片夹
     */
    @PostMapping("/folder/restore/{id}")
    @ResponseBody
    public Map<String, Object> restoreFolder(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCardFolder folder = folderService.getFolderById(id);

            if (folder == null) {
                result.put("success", false);
                result.put("message", "名片夹不存在");
                return result;
            }

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权恢复该名片夹");
                return result;
            }

            boolean success = folderService.restoreFolder(id);

            result.put("success", success);
            result.put("message", success ? "恢复名片夹成功" : "恢复名片夹失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "恢复名片夹失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 彻底删除名片夹
     */
    @DeleteMapping("/folder/remove/{id}")
    @ResponseBody
    public Map<String, Object> removeFolder(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCardFolder folder = folderService.getFolderById(id);

            if (folder == null) {
                result.put("success", false);
                result.put("message", "名片夹不存在");
                return result;
            }

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权删除该名片夹");
                return result;
            }

            boolean success = folderService.removeFolder(id);

            result.put("success", success);
            result.put("message", success ? "彻底删除名片夹成功" : "彻底删除名片夹失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "彻底删除名片夹失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 显示名片夹内容
     */
    @GetMapping("/folder/{id}")
    public String viewFolder(@PathVariable Integer id, Model model) {
        BusinessCardFolder folder = folderService.getFolderById(id);

        if (folder == null) {
            return "redirect:/user/businesscard";
        }

        User user = getCurrentUser();
        if (!folder.getUserId().equals(user.getId())) {
            return "redirect:/user/businesscard";
        }

        List<BusinessCard> cards = cardService.getCardsByFolderId(id);

        model.addAttribute("folder", folder);
        model.addAttribute("cards", cards);

        return "user/businesscard/folder";
    }

    /**
     * 创建单个名片
     */
    @PostMapping("/card/create")
    @ResponseBody
    public Map<String, Object> createCard(@RequestBody BusinessCard card) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCardFolder folder = folderService.getFolderById(card.getFolderId());

            if (folder == null) {
                result.put("success", false);
                result.put("message", "名片夹不存在");
                return result;
            }

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权在该名片夹中添加名片");
                return result;
            }

            boolean success = cardService.createCard(card);

            result.put("success", success);
            result.put("message", success ? "创建名片成功" : "创建名片失败");

            if (success) {
                result.put("card", card);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "创建名片失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 批量创建名片
     */
    @PostMapping("/card/batch-create")
    @ResponseBody
    @Transactional
    public Map<String, Object> batchCreateCards(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 检查并转换folderId
            Object folderIdObj = params.get("folderId");
            Integer folderId = null;
            if (folderIdObj instanceof Integer) {
                folderId = (Integer) folderIdObj;
            } else if (folderIdObj instanceof String) {
                try {
                    folderId = Integer.parseInt((String) folderIdObj);
                } catch (NumberFormatException e) {
                    result.put("success", false);
                    result.put("message", "名片夹ID格式错误");
                    return result;
                }
            } else {
                result.put("success", false);
                result.put("message", "名片夹ID参数类型错误");
                return result;
            }

            // 检查并转换cards列表
            Object cardsObj = params.get("cards");
            if (!(cardsObj instanceof List)) {
                result.put("success", false);
                result.put("message", "名片列表参数类型错误");
                return result;
            }

            List<?> rawCards = (List<?>) cardsObj;
            List<BusinessCard> cards = new ArrayList<>();

            try {
                for (Object item : rawCards) {
                    if (item instanceof Map) {
                        Map<String, Object> cardMap = (Map<String, Object>) item;
                        BusinessCard card = new BusinessCard();

                        // 设置名片属性，处理可能的null值
                        card.setName(cardMap.get("name") != null ? cardMap.get("name").toString() : null);
                        card.setGender(cardMap.get("gender") != null ? cardMap.get("gender").toString() : null);
                        card.setPhone(cardMap.get("phone") != null ? cardMap.get("phone").toString() : null);
                        card.setEmail(cardMap.get("email") != null ? cardMap.get("email").toString() : null);
                        card.setOrganization(cardMap.get("organization") != null ? cardMap.get("organization").toString() : null);
                        card.setPosition(cardMap.get("position") != null ? cardMap.get("position").toString() : null);
                        card.setAddress(cardMap.get("address") != null ? cardMap.get("address").toString() : null);
                        card.setRemark(cardMap.get("remark") != null ? cardMap.get("remark").toString() : null);

                        cards.add(card);
                    } else if (item instanceof BusinessCard) {
                        cards.add((BusinessCard) item);
                    } else {
                        throw new ClassCastException("名片数据格式错误");
                    }
                }
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "名片数据格式错误：" + e.getMessage());
                return result;
            }

            // 检查名片夹是否存在
            BusinessCardFolder folder = folderService.getFolderById(folderId);
            if (folder == null) {
                result.put("success", false);
                result.put("message", "名片夹不存在");
                return result;
            }

            // 检查权限
            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权在该名片夹中添加名片");
                return result;
            }

            // 设置所有名片的folderId
            for (BusinessCard card : cards) {
                card.setFolderId(folderId);
            }

            boolean success = cardService.batchCreateCards(cards);

            result.put("success", success);
            result.put("message", success ? "批量创建名片成功" : "批量创建名片失败");
            if (success) {
                result.put("cards", cards);
            }
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量创建名片失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 更新名片信息
     */
    @PostMapping("/card/update")
    @ResponseBody
    public Map<String, Object> updateCard(@RequestBody BusinessCard card) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCard existingCard = cardService.getCardById(card.getId());

            if (existingCard == null) {
                result.put("success", false);
                result.put("message", "名片不存在");
                return result;
            }

            BusinessCardFolder folder = folderService.getFolderById(existingCard.getFolderId());

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权修改该名片");
                return result;
            }

            boolean success = cardService.updateCard(card);

            result.put("success", success);
            result.put("message", success ? "更新名片成功" : "更新名片失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "更新名片失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 删除名片(移入回收站)
     */
    @PostMapping("/card/delete/{id}")
    @ResponseBody
    public Map<String, Object> deleteCard(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCard card = cardService.getCardById(id);

            if (card == null) {
                result.put("success", false);
                result.put("message", "名片不存在");
                return result;
            }

            BusinessCardFolder folder = folderService.getFolderById(card.getFolderId());

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权删除该名片");
                return result;
            }

            boolean success = cardService.deleteCard(id);

            result.put("success", success);
            result.put("message", success ? "删除名片成功" : "删除名片失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "删除名片失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 恢复名片
     */
    @PostMapping("/card/restore/{id}")
    @ResponseBody
    public Map<String, Object> restoreCard(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCard card = cardService.getCardById(id);

            if (card == null) {
                result.put("success", false);
                result.put("message", "名片不存在");
                return result;
            }

            BusinessCardFolder folder = folderService.getFolderById(card.getFolderId());

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权恢复该名片");
                return result;
            }

            boolean success = cardService.restoreCard(id);

            result.put("success", success);
            result.put("message", success ? "恢复名片成功" : "恢复名片失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "恢复名片失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 彻底删除名片
     */
    @DeleteMapping("/card/remove/{id}")
    @ResponseBody
    public Map<String, Object> removeCard(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCard card = cardService.getCardById(id);

            if (card == null) {
                result.put("success", false);
                result.put("message", "名片不存在");
                return result;
            }

            BusinessCardFolder folder = folderService.getFolderById(card.getFolderId());

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权删除该名片");
                return result;
            }

            boolean success = cardService.removeCard(id);

            result.put("success", success);
            result.put("message", success ? "彻底删除名片成功" : "彻底删除名片失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "彻底删除名片失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 条件查询名片
     */
    @PostMapping("/card/search")
    @ResponseBody
    public Map<String, Object> searchCards(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 获取ID参数（可能为null）
            Object idObj = params.get("id");
            Integer id = null;

            if (idObj != null) {
                if (idObj instanceof Integer) {
                    id = (Integer) idObj;
                } else if (idObj instanceof String) {
                    try {
                        id = Integer.parseInt((String) idObj);
                    } catch (NumberFormatException e) {
                        result.put("success", false);
                        result.put("message", "名片ID格式错误");
                        return result;
                    }
                }
            }

            // 如果提供了ID，则按ID查询单个名片
            if (id != null) {
                BusinessCard card = cardService.getCardById(id);
                if (card == null) {
                    result.put("success", false);
                    result.put("message", "名片不存在");
                    return result;
                }

                // 权限验证
                BusinessCardFolder folder = folderService.getFolderById(card.getFolderId());
                User user = getCurrentUser();
                if (folder == null || !folder.getUserId().equals(user.getId())) {
                    result.put("success", false);
                    result.put("message", "无权查看该名片");
                    return result;
                }

                result.put("success", true);
                result.put("cards", Arrays.asList(card));
                return result;
            }

            // 否则按folderId和isDeleted查询名片列表
            Object folderIdObj = params.get("folderId");
            Integer folderId = null;
            if (folderIdObj != null) {
                if (folderIdObj instanceof Integer) {
                    folderId = (Integer) folderIdObj;
                } else if (folderIdObj instanceof String) {
                    try {
                        folderId = Integer.parseInt((String) folderIdObj);
                    } catch (NumberFormatException e) {
                        result.put("success", false);
                        result.put("message", "名片夹ID格式错误");
                        return result;
                    }
                }
            }
            Boolean isDeleted = (Boolean) params.get("isDeleted");

            if (folderId == null) {
                result.put("success", false);
                result.put("message", "名片夹ID不能为空");
                return result;
            }

            // 调用服务层方法查询名片
            List<BusinessCard> cards = cardService.searchCards(params);
            result.put("success", true);
            result.put("cards", cards);

        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "查询名片失败：" + e.getMessage());
        }

        return result;
    }

    /*
     * 批量更新名片特定字段
     */
    @PostMapping("/card/batch-update")
    @ResponseBody
    @Transactional
    public Map<String, Object> batchUpdateCards(@RequestBody Map<String, Object> params) {
        Map<String, Object> result = new HashMap<>();

        try {
            // 1. 验证并转换folderId
            Object folderIdObj = params.get("folderId");
            Integer folderId = null;

            if (folderIdObj == null) {
                result.put("success", false);
                result.put("message", "名片夹ID不能为空");
                return result;
            }

            if (folderIdObj instanceof Integer) {
                folderId = (Integer) folderIdObj;
            } else if (folderIdObj instanceof String) {
                try {
                    folderId = Integer.parseInt((String) folderIdObj);
                } catch (NumberFormatException e) {
                    result.put("success", false);
                    result.put("message", "名片夹ID格式错误");
                    return result;
                }
            } else {
                result.put("success", false);
                result.put("message", "名片夹ID参数类型错误");
                return result;
            }

            // 2. 验证并转换cardIds列表
            Object cardIdsObj = params.get("cardIds");
            if (!(cardIdsObj instanceof List)) {
                result.put("success", false);
                result.put("message", "名片ID列表参数类型错误");
                return result;
            }

            List<Integer> cardIds = new ArrayList<>();
            try {
                for (Object item : (List<?>) cardIdsObj) {
                    if (item instanceof Integer) {
                        cardIds.add((Integer) item);
                    } else if (item instanceof String) {
                        try {
                            cardIds.add(Integer.parseInt((String) item));
                        } catch (NumberFormatException e) {
                            result.put("success", false);
                            result.put("message", "名片ID格式错误");
                            return result;
                        }
                    } else {
                        result.put("success", false);
                        result.put("message", "名片ID参数类型错误");
                        return result;
                    }
                }
            } catch (Exception e) {
                result.put("success", false);
                result.put("message", "名片ID列表解析失败：" + e.getMessage());
                return result;
            }

            // 3. 验证其他必填字段
            String fieldName = (String) params.get("fieldName");
            String newValue = (String) params.get("newValue");

            if (fieldName == null || fieldName.trim().isEmpty()) {
                result.put("success", false);
                result.put("message", "字段名不能为空");
                return result;
            }
            
            if (newValue == null) {
                result.put("success", false);
                result.put("message", "新值不能为null");
                return result;
            }

            // 4. 验证名片夹权限
            BusinessCardFolder folder = folderService.getFolderById(folderId);
            if (folder == null) {
                result.put("success", false);
                result.put("message", "名片夹不存在");
                return result;
            }

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权批量修改该名片夹中的名片");
                return result;
            }

            // 5. 调用服务层方法
            boolean success = cardService.batchUpdateCards(cardIds, fieldName, newValue);

            result.put("success", success);
            result.put("message", success ? "批量更新名片成功" : "批量更新名片失败");
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "批量更新名片失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 导入名片
     */
    @PostMapping("/card/import")
    @ResponseBody
    public Map<String, Object> importCards(@RequestParam("file") MultipartFile file, @RequestParam("folderId") Integer folderId) {
        Map<String, Object> result = new HashMap<>();

        try {
            BusinessCardFolder folder = folderService.getFolderById(folderId);

            if (folder == null) {
                result.put("success", false);
                result.put("message", "名片夹不存在");
                return result;
            }

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                result.put("success", false);
                result.put("message", "无权在该名片夹中导入名片");
                return result;
            }

            Map<String, Object> importResult = cardService.importCards(file, folderId);

            result.put("success", true);
            result.put("importResult", importResult);
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", "导入名片失败：" + e.getMessage());
        }

        return result;
    }

    /**
     * 导出名片
     */
    @GetMapping("/card/export/{folderId}")
    public ResponseEntity<byte[]> exportCards(@PathVariable Integer folderId) {
        try {
            BusinessCardFolder folder = folderService.getFolderById(folderId);

            if (folder == null) {
                return ResponseEntity.notFound().build();
            }

            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }

            byte[] excelData = cardService.exportCards(folderId);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", folder.getFolderName() + ".xlsx");

            return new ResponseEntity<>(excelData, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 根据查询条件导出名片
     */
    @GetMapping("/card/export-by-search")
    public ResponseEntity<byte[]> exportCardsByParams(
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String gender,
            @RequestParam(required = false) String phone,
            @RequestParam(required = false) String organization,
            @RequestParam(required = false) String position,
            @RequestParam(required = false) String address,
            @RequestParam(required = true) Integer folderId) {
        try {
            // 检查名片夹是否存在
            BusinessCardFolder folder = folderService.getFolderById(folderId);
            if (folder == null) {
                return ResponseEntity.notFound().build();
            }
            
            // 检查权限
            User user = getCurrentUser();
            if (!folder.getUserId().equals(user.getId())) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).build();
            }
            
            // 构建查询参数
            Map<String, Object> params = new HashMap<>();
            params.put("folderId", folderId);
            params.put("isDeleted", false); // 只导出未删除的名片
            
            if (name != null && !name.isEmpty()) {
                params.put("name", name);
            }
            if (gender != null && !gender.isEmpty()) {
                params.put("gender", gender);
            }
            if (phone != null && !phone.isEmpty()) {
                params.put("phone", phone);
            }
            if (organization != null && !organization.isEmpty()) {
                params.put("organization", organization);
            }
            if (position != null && !position.isEmpty()) {
                params.put("position", position);
            }
            if (address != null && !address.isEmpty()) {
                params.put("address", address);
            }
            
            byte[] excelData = cardService.exportCardsBySearchParams(params);
            
            String fileName = folder.getFolderName() + "_搜索结果.xlsx";
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            headers.setContentDispositionFormData("attachment", fileName);
            
            return new ResponseEntity<>(excelData, headers, HttpStatus.OK);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }

    /**
     * 获取当前登录用户
     */
    private User getCurrentUser() {
        HttpSession session = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getSession();
        return (User) session.getAttribute("user");
    }
}
